/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useMemo, useCallback, useState, useEffect, forwardRef } from "react";
import { Select, Row, Col, Button, Empty } from "antd";
import { isArray } from "lodash";
import citys from "@kb/citys";
import styles from "./Citys.less";
import { provinces } from "./config";

const Citys_picker = forwardRef((props, ref) => {
  const { selectted = [], value = [], onChange } = props;
  const [formatAddress, setFormatAddress] = useState([]);
  const [keywords, setKeywords] = useState("");

  useEffect(() => {
    const city_s = citys[1].filter(item => item);
    const provines_s = provinces.map(({ children, ...rest }) => ({
      ...rest,
      children: children.map(item => city_s.find(itemm => itemm.id == item)),
    }));
    setFormatAddress([...provines_s]);
  }, []);

  const handleButton = useCallback(
    item => {
      const { id, name } = item;
      let currentValue, _value;
      if (value) {
        _value = value.map(item => item.id);
        if (_value.includes(id)) {
          currentValue = value.filter(item => item.id != id);
        } else {
          currentValue = [...value, { id, name }];
        }
      } else {
        currentValue = [{ id, name }];
      }
      handleSearch();
      _onChange(currentValue);
    },
    [value]
  );
  const checkButtonDisabled = useCallback(
    id => {
      return selectted.some(item => item.id == id);
    },
    [selectted]
  );
  const _onChange = useCallback(data => {
    onChange(data);
  }, []);

  // 记录搜索关键词
  const handleSearch = useCallback((value = "") => {
    setKeywords(value);
  }, []);

  // 格式化的value
  const formattedValue = useMemo(() => value.map(item => item.name), [value]);

  // 手动控制弹窗展开与关闭
  const handleDropDownVisibleChange = useCallback(visbile => {
    visbile && handleSearch();
  }, []);

  // 触发切换
  const handleChange = useCallback(
    data => _onChange(data.length ? value.filter(item => data.includes(item.name)) : []),
    [value]
  );

  // 自定义地区分组渲染
  const dropdownRender = useCallback(
    () => {
      const list = keywords
        ? formatAddress
            .filter(item => item.children.some(itemm => itemm.name === keywords))
            .map(({ children, ...rest }) => ({
              ...rest,
              children: children.filter(itemm => itemm.name === keywords),
            }))
        : formatAddress;
      return (
        <>
          {list.length > 0 ? (
            list.map(item => (
              <div
                className={styles.province_citys_row}
                key={item.key}
                onMouseDown={e => e.preventDefault()}
              >
                <Row>
                  <Col span={6}>
                    <div className={styles.province_citys_title}>{item.label}</div>
                  </Col>
                  <Col span={18}>
                    {item.children.map(_key => {
                      return (
                        <Button
                          size="small"
                          disabled={checkButtonDisabled(_key.id)}
                          type={formattedValue.includes(_key.name) ? "primary" : "default"}
                          onClick={handleButton.bind(null, _key)}
                          key={_key.id}
                          className={styles.province_citys_tag}
                        >
                          {_key.name}
                        </Button>
                      );
                    })}
                  </Col>
                </Row>
              </div>
            ))
          ) : (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              className="ant-empty-small"
              description={keywords ? "未匹配到对应地区，请输入其他关键词" : "暂无数据"}
            />
          )}
        </>
      );
    },
    [selectted, value, formatAddress, keywords]
  );

  return (
    <Select
      ref={ref}
      placeholder="请选择发往地区"
      allowClear
      showArrow
      showSearch
      mode="multiple"
      style={{ width: "70%" }}
      dropdownRender={dropdownRender}
      value={formattedValue}
      onSearch={handleSearch}
      onDropdownVisibleChange={handleDropDownVisibleChange}
      onChange={handleChange}
      dropdownClassName={styles.dropdownClassName}
    />
  );
});

export default React.memo(Citys_picker);
